//
//  UITextView+Emoticon.swift
//  测试键盘
//
//  Created by Tanenbaum on 15/8/7.
//  Copyright © 2015年 GZJ. All rights reserved.
//

import UIKit

extension UITextView {
    
    
    func insertEmoticon(emoticon:Emoticon) {
        
        if emoticon.removeEmoticon {
            
            deleteBackward()
            return
        }
        
        if emoticon.emoji != nil {
            replaceRange(selectedTextRange!, withText: emoticon.emoji!)
            return
        }
        if emoticon.chs != nil {
            
            let attachment = EmoticonAttachment()
            attachment.chs = emoticon.chs
            attachment.image = UIImage(contentsOfFile: emoticon.imagePath)
            
            let h = font!.lineHeight
            attachment.bounds = CGRect(x: 0, y: -4, width: h, height: h)
            
            let imageText = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attachment))
            imageText.addAttribute(NSFontAttributeName, value: font!, range: NSMakeRange(0, 1))
            
            let strM = NSMutableAttributedString(attributedString: attributedText)
            strM.replaceCharactersInRange(selectedRange, withAttributedString: imageText)
            
            let range = selectedRange
            attributedText = strM
            
            selectedRange = NSRange(location: range.location + 1 , length: 0)
            delegate?.textViewDidChange!(self)
        }
        
        
    }

    
    var emoticonText: String {
        
        let attString = attributedText
        var strM = String()
        attString.enumerateAttributesInRange(NSMakeRange(0, attString.length), options: NSAttributedStringEnumerationOptions(rawValue: 0)) { (dict,range, _) -> Void in
            
            if let attachment = dict["NSAttachment"] as? EmoticonAttachment {
                strM += attachment.chs!
            }else {
                strM += (attString.string as NSString).substringWithRange(range)
            }
        }
        
        return strM
    }
    
    
}
